package com.tuton.javanet.chapter02;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Receiver {

	private int port = 8000;
	private ServerSocket serverSocket;
	
	private static int stopWay = 1;
	private final int NATRUALWAY = 1;
	private final int SUNDDENWAY = 2;
	private final int SOCKETWAY  = 3;
	private final int OUTPUTWAY  = 4;
	private final int SERVERWAY  = 5;
	
	public Receiver() throws IOException {
		this.serverSocket = new ServerSocket(port);
		System.out.println("The receiver Server was started....");
	}
	
	public static void main(String[] args) throws IOException, InterruptedException {
		if(args.length > 0) {
			stopWay = Integer.parseInt(args[0]);
			System.out.println("stopWayNumber = " + stopWay);
		}
		new Receiver().receiver();
	}

	private void receiver() throws IOException, InterruptedException {
		Socket socket = null;
		socket = serverSocket.accept();
		BufferedReader br = this.getReader(socket);
		
		for(int i = 0; i < 20; i++) {
			String msg = br.readLine();
			System.out.println("Got a message : " + msg);
			
			if(2 == i) {
				if(this.SUNDDENWAY == stopWay) {
					System.out.println("Sundenly shut down this program.....");
					System.exit(0);
				} else if(this.SOCKETWAY == stopWay) {
					socket.close();
					System.out.println("Socket close exit this program....");
					break;
				} else if(this.OUTPUTWAY == stopWay) {
					socket.shutdownInput();
					System.out.println("OutputStream close before shut down this program....");
				} else if(this.SERVERWAY == stopWay) {
					socket.close();
					break;
				}
			}	
		}
		
		if(this.NATRUALWAY == stopWay) {
			System.out.println("Shutdown this program in a natural way...");
			serverSocket.close();
			socket.close();
		}
	}
	

	private BufferedReader getReader(Socket socket) throws IOException {
		InputStream socketIn = socket.getInputStream();
		return new BufferedReader(new InputStreamReader(socketIn));
	}
	
	
}
